package com.presalept.manipulatedata;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.presalept.polodo.ProjectMemberDO;

public class CreateProjectMember {
	
	//insert projectmembers
	
	public static int InsertProjectMemeber(List<ProjectMemberDO> projetmember) throws SQLException{
		
		int InsertResult = 0;
		Connection dbConn = null;
		PreparedStatement dbProjectMemberStmt = null;
		ResultSet dbRs = null;
		int[] insertProjectMemberResult;
	
		String dbProjectMemberSql = "INSERT INTO relationofprojectanduser (projectid,userid,purelationstatus,createdate)"
				+ " VALUES(?,?,?,?); ";
		try{
			
			dbConn = DbManager.getConnection();		
			
			dbProjectMemberStmt = dbConn.prepareStatement(dbProjectMemberSql);
			
			//insert users into the relationprojectanduser for the project
			
			for(Iterator<ProjectMemberDO> i = projetmember.iterator(); i.hasNext();){
				
				ProjectMemberDO pmdo = i.next();
				
				//when OprateType == 1 then insert it
				
				if(pmdo.getOperateType() == 1){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");  
			        Date createdate = null;  
			        try {  
			        	
			        	createdate = sdf.parse(pmdo.getCreatedate()); 
	  
			        } catch (ParseException e) {  
			            e.printStackTrace();  
			        }       
			        java.sql.Date sqlcreateDate = new java.sql.Date(createdate.getTime()); 
					
					dbProjectMemberStmt.setInt(1, pmdo.getProjectId());
					dbProjectMemberStmt.setInt(2, pmdo.getUserId());
					dbProjectMemberStmt.setInt(3, pmdo.getPurelationstatus());
					dbProjectMemberStmt.setDate(4, sqlcreateDate);
					
					dbProjectMemberStmt.addBatch();			
				}
			}
			
			
			insertProjectMemberResult = dbProjectMemberStmt.executeBatch();

			boolean isInsertRight = false;
			for(int i = 0; i < insertProjectMemberResult.length; i++){
					
				//if some record has del error, then rollback
					
					if(insertProjectMemberResult[i] == 0){
						dbConn.rollback();
						break;
					}
					
					isInsertRight = true;
				}
			
			if(isInsertRight){
				dbConn.commit();
				InsertResult = 1;
				
			}
			
		}finally{
			if (dbRs != null) dbRs.close();
			if (dbConn != null) dbConn.close();			
		}
		
		return InsertResult;
	}
}
